package com.hp.bon.sgw.wh.utils;

import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * 错误更正
 * @date 2020/07/16 15:15:15
 */
public class ResultCodeUtil {
    private static final Logger logger = LoggerFactory.getLogger(ResultCodeUtil.class);
    /**
     * 更更新错误码
     * @param resultCode 需要转换的错误码
     * @param configCode 配置里错误码json串
     * @param defaultResultCode 配置中无匹配时返回的错误码
     * @return 转换后错误码
     */
    public static String updateResultCode(Object resultCode,String configCode,String defaultResultCode){
        logger.info("=========updateResultCode:start");
        logger.info("=========updateResultCode:resultCode="+resultCode);
        logger.info("=========updateResultCode:configCode="+configCode);
        logger.info("=========updateResultCode:defaultResultCode="+defaultResultCode);
        String newResultCode=defaultResultCode;
        if(resultCode == null || StringUtils.isEmpty(resultCode.toString())){
            resultCode="-1";
        }
        //0成功不需要转换
        if(NumberUtils.isDigits(resultCode.toString()) && Integer.valueOf(resultCode.toString()) == 0){
            newResultCode="0";
        }else{
            JSONObject jsonObject = JSONObject.fromString(configCode);
            Object o = jsonObject.opt(resultCode.toString());
            if(o != null){
                newResultCode=o.toString();
            }
        }
        logger.info("=========updateResultCode:newResultCode="+newResultCode);
        logger.info("=========updateResultCode:end");
        return newResultCode;
    }

    public static void main(String[] args) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("resultCode","00000000000");
        String code=updateResultCode(data.get("resultCode"),"{\"501\":\"1003-501\",\"1200\":\"1003-1200\",\"7003\":\"1017-7003\",\"241\":\"1018-241\",\"-1\":\"2006-1\"}","001");
        data.put("resultCode",code);
        System.out.println(new Gson().toJson(data));

    }
}
